package com.tangqihang229350526.mynote

import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import com.tangqihang229350526.mynote.database.UserDatabase
import com.tangqihang229350526.mynote.databinding.ActivityLoginBinding
import com.tangqihang229350526.mynote.repository.UserRepository
import com.tangqihang229350526.mynote.viewmodel.LoginViewModel
import com.tangqihang229350526.mynote.viewmodel.RegisterViewModel

class LoginActivity : AppCompatActivity() {
    private var binding: ActivityLoginBinding? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityLoginBinding.inflate(layoutInflater)
        setContentView(binding!!.root)

        //登录
        val viewModel = ViewModelProvider(this)[LoginViewModel::class.java]
        binding!!.btnLogin.setOnClickListener {
            val username = binding!!.etUsername.text.toString()
            val password = binding!!.etPassword.text.toString()
            val u = UserDatabase(this)
            UserRepository.instance?.login(u,viewModel, username, password)
        }
        viewModel.isRight().observe(this) { aBoolean ->
            if (aBoolean) {
                startActivity(Intent(this@LoginActivity, MainActivity::class.java))
                Toast.makeText(this@LoginActivity, "登录成功", Toast.LENGTH_LONG).show()
                finish()
            } else {
                Toast.makeText(this@LoginActivity, "账号或密码错误", Toast.LENGTH_LONG).show()
            }
        }

        //注册
        val registerModel = ViewModelProvider(this)[RegisterViewModel::class.java]
        binding!!.btnRegister.setOnClickListener {
            val username = binding!!.etUsername.text.toString()
            val password = binding!!.etPassword.text.toString()
            val u = UserDatabase(this)
            UserRepository.instance?.register(u,registerModel, username, password)
        }
        registerModel.isRegisterOk().observe(this) {aBoolean ->
            if (aBoolean) {
                Toast.makeText(this@LoginActivity, "注册成功", Toast.LENGTH_LONG).show()
            } else {
                Toast.makeText(this@LoginActivity, "注册失败,用户存在", Toast.LENGTH_LONG).show()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        binding = null
    }
}